package com.sx.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author Administrator
 * @Description
 * @Date 2020/11/2 16:21
 * <p>
 * 实现：一个channel实现文件的读和写
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
//        文件输入流
        FileInputStream fileInputStream = new FileInputStream("d://file.txt");
        FileChannel channel01 = fileInputStream.getChannel();

//        文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream("d://file02.txt");
        FileChannel channel02 = fileOutputStream.getChannel();

//        创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

//        循环读取文件内容——边读边写
        while (true) {
            buffer.clear();
//            将buffer中的内容读取到channel中
            int read = channel01.read(buffer);
            System.out.println("read：" + read);
            if(read == -1){
//                表示读取完毕
                break;
            }
//            将buffer中的内容写入到channel02中
//            转换流
            buffer.flip();
            channel02.write(buffer);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }
}
